package movee.io.cmd.service;

import feign.FeignException;
import feign.RequestInterceptor;
import feign.RetryableException;
import feign.Retryer;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;

import java.util.Date;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 *
 *
 * @author movee
 */
public class CmdServiceReadFeignConfig {

    private final ErrorDecoder defaultErrorDecoder = new ErrorDecoder.Default();

    /**
     * 自定义重试机制
     * @return Retryer
     */
    @Bean
    public Retryer feignRetryer() {
        // 最大请求次数为2，初始间隔时间为100ms，下次间隔时间1.5倍递增，重试间最大间隔时间为1s，
        return new Retryer.Default(100, SECONDS.toMillis(1), 2);
    }

    @Bean
    public ErrorDecoder feignError() {
        return (key, response) -> {
            if (response.status() >= 500) {
                FeignException exception = FeignException.errorStatus(key, response);
                return new RetryableException(
                        response.status(),
                        exception.getMessage(),
                        response.request().httpMethod(),
                        new Date(),
                        response.request());
            }

            // 其他异常交给Default去解码处理
            return defaultErrorDecoder.decode(key, response);
        };
    }

    /**
     * fegin 拦截器
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            requestTemplate.header("Authorization", CmdServiceConfig.token);
            requestTemplate.header("Content-Type", "application/json");
            requestTemplate.header("Accept", "application/json");
        };
    }

}
